#include "widget.h"
#include "ui_widget.h"
#include <QNetworkDatagram>

//编写udp服务器

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    socket = new QUdpSocket(this);

    connect(socket,&QUdpSocket::readyRead,this,&Widget::handle);

    socket->bind(QHostAddress::Any,9090);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::handle()
{
    //读取消息
    QNetworkDatagram gram = socket->receiveDatagram();

    //执行处理函数
    QString str = udphandle(gram);

    //构建返回对象
    QNetworkDatagram ret_gram(str.toUtf8(),gram.senderAddress(),gram.senderPort());

    //发送回去
    socket->writeDatagram(ret_gram);

    //显示观察
    QString show_str = "get: " + gram.senderAddress().toString() + " " + QString::number(gram.senderPort()) + " " + gram.data();
    ui->listWidget->addItem(show_str);
}

QString Widget::udphandle(QNetworkDatagram & data)
{
    return "server echo: " + data.data();
}
